%US banks and Inequality
%code for calculating asset distribution (for year = 2012)
%by Earth Tantasith 
%8 Mar 2021

opts = spreadsheetImportOptions("NumVariables", 4);

% Specify sheet and range
opts.Sheet = "Sheet1";
opts.DataRange = "A1:D27508"; 

% Specify column names and types
opts.VariableNames = ["cert_new", "fips", "depsumbr", "asset"];
opts.VariableTypes = ["double", "double", "double", "double"];

% Import the data
data = readtable("/Volumes/TOSHIBA EXT/FDIC data/2012/sd_call_2012_matlab.xlsx",opts, "UseExcel", false);

%% Convert to output type

data = table2array(data);

%% Clear temporary variables

clear opts;

for j= 1:7081
  if j == 1
cert_new = data(:,1) == j;
v = data(cert_new,3);
s = data(cert_new,4);
s = s(1);
v = v';
[m,n] = size(v);

A = zeros(n,n);

for i = 1:n
    if i == n
        A(i,:) = 1;
    else
    A(i,i) = 1/v(i);
    A(i,i+1) = -1/v(i+1);
    end
end

B = zeros(n,1);
B(n) = s;

X = linsolve(A,B);
AsDis = X;
check = sum(X);
  else
cert_new = data(:,1) == j;
v = data(cert_new,3);
s = data(cert_new,4);
s = s(1);
v = v';
[m,n] = size(v);

A = zeros(n,n);

for i = 1:n
    if i == n
        A(i,:) = 1;
    else
    A(i,i) = 1/v(i);
    A(i,i+1) = -1/v(i+1);
    end
end

B = zeros(n,1);
B(n) = s;
X = linsolve(A,B);
AsDis = [AsDis;X];
check = sum(X);
  end  
end
cert = data(:,1)
export = horzcat(cert,AsDis)
export = array2table(export)
writetable(export,'asset_dis_2012.xlsx')